package com.iwop.moto.auth;


import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.model.User;
import com.iwop.moto.utils.http.SessionUtils;
import com.iwop.moto.utils.stringUtil.StringUtils;
import com.iwop.moto.utils.weixin.WeixinUtil;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/***
 * 采用标签方式进行用户权限拦截
 * 用户权限拦截器
 * @author huyuangui
 * @time 2015-9-25 下午02:41:11
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = Logger.getLogger(AuthInterceptor.class);
    public void afterCompletion(HttpServletRequest requst,
                                HttpServletResponse response, Object arg2, Exception arg3)
            throws Exception {

    }

    public void postHandle(HttpServletRequest requst,
                           HttpServletResponse response, Object arg2, ModelAndView arg3)
            throws Exception {

    }
    /**
     * 功能:所有请求验证 [get | post]请求
     * Controller 方法体上 @LoginAuth(isval = true) 需要登录验证
     * 1、验证是否为微信 根据微信的openid
     */
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String path=request.getContextPath();
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            LoginAuth authPassport = ((HandlerMethod) handler).getMethodAnnotation(LoginAuth.class);
            if (authPassport == null || (authPassport.isval()==false && authPassport.isWx()==false)) {
                log(request,"user","");
                return true;
            } else {
                if(authPassport.isWx()){/** 是微信请求  SpringMVC 注解 @LoginAuth(isWx = true) **/
                    SuperRecordModel wxUeseInfo = (SuperRecordModel)request.getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
                    if(wxUeseInfo==null){
                        String reqUrl = request.getRequestURI().toString();
                        String param = request.getQueryString();
                        if(param != null) {
                            reqUrl += "?" + param;
                        }
                        WeixinUtil.Oauth2Authorize(response,Comm.WX_RETURN_URL ,reqUrl);
                        return false;
                    } else {
                        /** 判断微信用户网页授权token是否过期,过期则重新请求授权 **/
                        Long tokenTime = new Date().getTime() - 10000;//当前系统的时间 - 10s(秒)
                        if(tokenTime > (Long) wxUeseInfo.get("token_time")){
                           SuperRecordModel RefreshToken = WeixinUtil.Oauth2RefreshToken(wxUeseInfo.getString("refresh_token"));
                           wxUeseInfo.putAll(RefreshToken);
                           wxUeseInfo.put("token_time",tokenTime + ((Integer)wxUeseInfo.get("expires_in") * 1000));
                           request.getSession().setAttribute(Comm.SESSION_WEIXIN_ID,wxUeseInfo);
                        }
                        return true;
                    }
                } else if(authPassport.isval()||authPassport.isAdminVal()){
                    String session_id=request.getParameter("session_id");
                    if(StringUtils.isEmpty(session_id)){
                        ResponseBody responseBody=((HandlerMethod) handler).getMethodAnnotation(ResponseBody.class);
                        if(responseBody!=null){
                            ResultModel resultModel=new ResultModel();
                            resultModel.setCode(-1);
                            resultModel.setMem("您还没有登录，请先登录");
                            PrintWriter pw= response.getWriter();
                            pw.write(JSONObject.toJSONString(resultModel));
                            pw.close();
                            return false;
                        }else{
                            if(authPassport.isval()) {
                                response.sendRedirect(path + "/user_login");
                            }else{
                                response.sendRedirect(path + "/admin_login");
                            }
                        }
                    }else{
                        if(authPassport.isval()){
                            User user=JSON.parseObject(SessionUtils.getValueFromSession(session_id).toString(),User.class);
                            log(request,"user",user==null?"":user.getSid());
                            if(user==null){
                                ResponseBody responseBody=((HandlerMethod) handler).getMethodAnnotation(ResponseBody.class);
                                if(responseBody!=null){
                                    ResultModel resultModel=new ResultModel();
                                    resultModel.setCode(-1);
                                    resultModel.setMem("您还没有登录，请先登录");
                                    PrintWriter pw= response.getWriter();
                                    pw.write(JSONObject.toJSONString(resultModel));
                                    pw.close();
                                    return false;
                                }else{
                                    if(authPassport.isval()) {
                                        response.sendRedirect(path + "/user_login");
                                    }else{
                                        response.sendRedirect(path + "/admin_login");
                                    }
                                }
                            }
                        }else{

                        }
                    }
                }else {
                    log(request,"user","");
                    return true;
                }
            }
        }else{
            log(request,"app",request.getParameter("sid"));
        }
        return true;
    }
    private void log(HttpServletRequest request ,String type,String id){
        StringBuffer sb=new StringBuffer();
        try {
            sb.append(type+"|"+id+"|");
            sb.append(request.getRequestURI()+"?");
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                String[] paramValues = request.getParameterValues(paramName);
                if (paramValues.length == 1) {
                    String paramValue = paramValues[0];
                    if (paramValue.length() != 0) {
                        sb.append(paramName+"="+paramValue+"&");
                    }
                }
            }
            logger.info(sb.toString());
        } catch (Exception e) {
            logger.info(sb.toString());
        }
    }
}